<template>
  <view class="good-wrap">
    <view class="header">
      <view class="search_row">
        <view class="search">
          <view class="search__icon iconfont icon-sousuo" />
          <input class="search__input" type="text" :value="name" @input="handleSearch" @confirm="handleConfirm"
            placeholder="输入商品名" />
        </view>
      </view>
      <!-- tab 切换 -->
      <view class="tab-box">
        <u-tabs :list="classList" :current="current" :fontSize="28" :isScroll="isScroll" bgColor="#ffffff"
          inactiveColor="#999999" @change="handleTabChange" :active-item-style="{ color: '#333' }"
          :bar-style="{ background: '#FEDD00', borderRadius: '100rpx' }"></u-tabs>
      </view>
    </view>
    <view class="list">
      <view class="good_item" v-for="(goodInfo, index) in items" :key="index" @tap="handleToDetail(goodInfo)">
        <view class="left_part">
          <view class="good_img_item">
            <img :src="goodInfo.thumbs[0]" class="good_img" />
          </view>
        </view>
        <view class="right_part">
          <view class="right_part_top">
            <view class="pay_type">{{
                goodInfo.online_pay === 1 ? '在线支付' : '免费使用'
            }}</view>
            <view class="title">{{ goodInfo.item_name }}</view>
          </view>

          <view class="item_info">
            <view class="good_price_row">
              <view class="good_price">
                <view class="price_symbol" v-if="goodInfo.price === 0"></view>
                <view class="price_symbol" v-else >¥</view>
                <view class="price_text"  v-if="goodInfo.price !== 0"> {{ (goodInfo.price / 100).toFixed(2) }}</view>
                <view class="price_text_free" v-else >免费使用</view>
              </view>
              <view class="good_num">
                <uNumberBox minValue="0" :maxValue="goodInfo.stock" :value="goodInfo.cnt"
                  @changeNumber="changeListItemNumber($event, goodInfo)" />
              </view>
            </view>
            <view class="operation_row">
              <view class="stock">{{ `库存 ${goodInfo.stock}` }}</view>
              <view class="count">浏览 {{ goodInfo.view_number }}</view>
              <!-- <view
                class="btn_add_good"
                @tap.stop="addGoodsToShoppingCart(goodInfo)"
                >加入购物车</view
              > -->
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="full-green" v-if="!isEmpty">
        <load-more :status="loadingStatus" />
      </view>
      <view v-else>
        <u-empty description="暂无商品～" />
      </view>
    <view class="content">
      <!-- <view class="shopping_cart_tips">满30元后，平台会购买一柱双色球福利彩票哦</br>邀您共享50%奖金，可在订单详情页查看号码</view> -->
      <view class="footer">
        <view>
          <img src="../../static/goods/shopping_cart.png" class="shopping_cart" @tap="gotoShoppingCart()" />
        </view>
        <view class="total_fee_warp">
          <view>
            <text class="price_symbol">¥</text>
            <text class="total_fee">{{ (totalFee / 100).toFixed(2) || 0 }}</text>
          </view>
          <view class="short_num">{{ totalFee < 2000 ? `还差${((2000 - totalFee) / 100).toFixed(2)}元即可免费配送` : '为您免费配送上门' }}</view>
          </view>
          <view class="place_btn" @tap="gotoSettlement()">下单</view>
        </view>
    </view>
      <uni-popup ref="shoppingCart" type="bottom">
        <view class="shopping_cart_layout">
          <scroll-view scroll-y="true" class="shopping_cart_infos">
            <!-- <view
            v-for="item in shoppingCartInfos"
            :key="item.itemId"
            class="good_info"
          >
            <checkbox-group @change="changeCheckGood(item)">
              <checkbox :checked="item.checked" />
            </checkbox-group>
            <img :src="item.url" class="good_img" />
            <view>
              <view>{{ item.item_name }}</view>
              <view>
                <view>{{ (item.price / 100).toFixed(2) }}</view>
                <uni-number-box
                  :min="1"
                  :value="item.cnt"
                  v-on:change="changeShoppingCartGoodNumber($event, item)"
                />
              </view>
            </view>
          </view> -->
            <view v-for="item in shoppingCartInfos" :key="item.itemId" class="good_info">
              <!-- 这一块要抽组件 -->
              <view class="good_item">
                <view class="left_part">
                  <view class="good_img_item">
                    <img :src="item.thumbs[0]" class="good_img" />
                  </view>
                </view>
                <view class="right_part">
                  <view class="right_part_top">
                    <view class="pay_type">{{
                        item.online_pay === 1 ? '在线支付' : '货到付款'
                    }}</view>
                    <view class="title">{{ item.item_name }}</view>
                  </view>

                  <view class="item_info">
                    <view class="good_price_row">
                      <view class="good_price">
                        <view class="price_symbol" v-if="item.price === 0"></view>
                        <view class="price_symbol" v-else >¥</view>
                        <view class="price_text"  v-if="item.price !== 0">{{ (item.price / 100).toFixed(2) }}</view>
                        <view class="price_text_free" v-else > 免费使用</view>
                      </view>
                      <view class="good_num">
                        <uNumberBox :maxValue="item.stock" minValue="0" :value="item.cnt"
                          @changeNumber="changeListItemNumber($event, item)" />
                      </view>
                    </view>
                    <view class="operation_row">
                      <view class="stock">{{ `库存 ${item.stock || ''}` }}</view>
                      <view class="count">浏览 {{ item.view_number || '' }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
          <!-- <view class="settlement_row">
          <view class="total_fee"
            >合计：{{ (totalFee / 100).toFixed(2) }}元</view
          >
          <button
            class="mini-btn btn_goto_settlement"
            type="default"
            size="mini"
            @tap="gotoSettlement()"
          >
            去结算
          </button>
        </view> -->
        </view>
      </uni-popup>

      <!-- <uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog
        :type="msgType"
        cancelText="关闭"
        confirmText="同意"
        title="通知"
        content="欢迎使用 uni-popup!"
        @confirm="dialogConfirm"
				@close="dialogClose"
      />
		</uni-popup> -->
    </view>
</template>

<script>
import get from 'lodash/get';
import { defaultHeader } from '@/tool/static-img';
import { uniPopup, uniNumberBox } from '@dcloudio/uni-ui';
import loadMore from '@/components/load-more.vue';
import uEmpty from '@/basic-components/u-empty/index.vue';

// 倒计时
import moreLoadMixins from '@/common/load-more';

import { momentDate } from '@/tool';

import {
  GOOD_LIST,
  GOOD_CLASS,
  SHOPPING_CART_INFO,
  ADD_GOODS_SHOP_CAR,
} from '@/api/good';
import countDownMixins from './mixins/count-down';
// import countBox from './components/count-box.vue';
import uTabs from '@/basic-components/u-tabs/index.vue';
import uNumberBox from '@/basic-components/u-number-box/index.vue';

export default {
  components: {
    // countBox,
    loadMore,
    uEmpty,
    uTabs,
    uniPopup,
    uniNumberBox,
    uNumberBox,
  },
  mixins: [moreLoadMixins, countDownMixins],
  data() {
    return {
      shopId: '',
      shopType:'',
      defaultHeader,
      name: '',
      // tab
      // tab切换
      isScroll: false,
      current: 0,
      totalFees:0,
      classList: [],
      shoppingCartInfos: [],
      shoppingCarId: '',
      totalFee: 0,
    };
  },
  async onLoad({ id, name,shopType }) {
    await this.getBindLoginStatus();
    this.shopId = id;
    this.shopType=shopType;
    uni.setNavigationBarTitle({
      title: decodeURIComponent(name),
    });
    // 类目
    await this.getClass();
    // 列表信息
    this.resetInit();
    this.totalFees=uni.getStorageSync(this.shopId+'shopCar');
  },

  async onPullDownRefresh() {
    // 初始化
    await this.resetInit();
    // 类目
    this.getClass();
    uni.stopPullDownRefresh();
  },
  methods: {
    getClass() {
      return new Promise ((resolve, reject) => {
          this.$http.get(GOOD_CLASS, 
          {
            page: 1,
            per_page: 100,
            shop_id: this.shopId,
          })
          .then((res) => {
            this.classList = res.data;
            if (this.classList.length > 5) {
              this.isScroll = true;
            } else {
              this.isScroll = false;
            }
            resolve(res.data)
          },(err) => {
            reject(err);
					})
        })
    },
    // changeCheckGood(goodInfo) {
    //   let totalFee = this.totalFee;
    //   this.shoppingCartInfos = this.shoppingCartInfos.map((item) => {
    //     if (goodInfo.itemId === item.itemId) {
    //       totalFee = item.checked
    //         ? totalFee - item.price * item.cnt
    //         : totalFee + item.price * item.cnt;
    //       return {
    //         ...item,
    //         checked: !item.checked,
    //       };
    //     } else {
    //       return item;
    //     }
    //   });
    //   this.totalFee = totalFee;
    // },
    handleTabChange(index) {
      if (this.current === index) {
        return;
      }
      this.totalFees=uni.getStorageSync(this.shopId+'shopCar');
      this.current = index;
      this.resetInit();
    },
    handleSearch(e) {
      // 搜索
      this.name = e.detail.value;
    },
    handleConfirm() {
      // 确认搜索
      this.resetInit();
    },
    handleToDetail(item) {
      this.$navigate({
        page: 'goodDetail',
        params: {
          id: item.id,
          shopId: this.shopId,
        },
      });
    },
    changeListItemNumber(value, item) {
      const itemsTemp = this.items?.map((good) => {
        if (good?.id === item?.id) {
          return {
            ...good,
            cnt: value,
          }
        }
        return {
          ...good,
        }
      });

      const shoppingCartInfosTemp = itemsTemp?.filter(it => it?.cnt);

      const totalFeeTemp = shoppingCartInfosTemp?.reduce((pre, it) => pre + (it?.price * it?.cnt), 0);
     
      if(!this.totalFees ||this.shoppingCartInfos?.length < 1 ){
        this.totalFees=0;
      }
      this.items = [...itemsTemp];
      this.totalFee = totalFeeTemp+this.totalFees;
      this.shoppingCartInfos = shoppingCartInfosTemp;
      uni.setStorageSync(this.shopId+'shopCar',this.totalFee);
      
    },

    // changeShoppingCartGoodNumber(value, item) {
    //   if(value === 0) {
    //     this.$refs.alertDialog.open();
    //   }

    //   let totalFeeTemp = 0;
    //   const shoppingCartInfos = this.shoppingCartInfos.map((good) => {
    //     if (good.itemId === item.itemId) {
    //       if (good.checked) {
    //       totalFeeTemp += good.price * value;
    //       }
    //       return {
    //         ...good,
    //         cnt: value,
    //         checked: value ? good.checked : false,
    //       };
    //     } else {
    //       if (good.checked) {
    //       totalFeeTemp += good.price * good.cnt;
    //       }
    //       return good;
    //     }
    //   });

    //   this.shoppingCartInfos = [...shoppingCartInfos];
    //   this.totalFee = totalFeeTemp;
    // },
    async gotoShoppingCart() {
      // const res = await this.$http.get(SHOPPING_CART_INFO, {
      //   shop_id: this.shopId,
      // });
      // const shoppingCartInfos = get(res, 'data.shopping_items', 'null');
      if (this.shoppingCartInfos?.length < 1) {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '购物车是空的哦',
          duration: 3000,
        });
        return;
      }
      // const shoppingCartId = get(res, 'data.id', 'null');
      // let totalFee = 0;
      // this.shoppingCartInfos = (JSON.parse(shoppingCartInfos) || []).map(
      //   (item) => {
      //     totalFee += item.price * item.cnt;
      //     return { ...item, checked: true };
      //   }
      // );
      // this.totalFee = totalFee;
      // this.$refs.shoppingCart.open();
      // this.shoppingCarId = shoppingCartId;

      this.$refs.shoppingCart.open();

    },
    gotoSettlement() {
      // const goodInfos = this.shoppingCartInfos.filter((goodinfo) => {
      //   return goodinfo.checked;
      // });
      if (this.shoppingCartInfos?.length < 1) {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '购物车是空的哦',
          duration: 3000,
        });
        return;
      }
      this.$navigate({
        page: 'confirmOrder',
        params: {
          goodInfos: JSON.stringify(this.shoppingCartInfos),
          totalFee: this.totalFee,
          shopId: this.shopId,
          shoppingCarId: 1, // 随便传个
          // shoppingCarId: this.shoppingCarId,
        },
      });
    },
    // async addGoodsToShoppingCart(goods) {
    //   const res = await this.$http.post(ADD_GOODS_SHOP_CAR, {
    //     shop_id: this.shopId,
    //     itemId: goods.id,
    //     operateType: 'add',
    //   });
    //   if (res.code === 200) {
    //     uni.showToast({
    //       icon: 'sucess',
    //       mask: true,
    //       title: '添加成功',
    //       duration: 3000,
    //     });
    //   }
    // },
    initData() {
      // 列表搜索
      const params = {
        page: this.pages.currentPage,
        per_page: this.pages.perPage,
        shop_id: this.shopId,
        shop_type:this.shopType,
        region_id:uni.getStorageSync('regionId'),
      };
      console.log('this.shopType===== ',this.shopType);
      // params.start = 'on';
      if (this.name) {
        params.name = this.name;
      }
      if (!this.current) {
        this.current=0;
      }
      params.item_type_id = this.classList[this.current].id;
      return this.$http.get(GOOD_LIST, params).then((res) => {
        const { data, last_page, current_page, total } = res;

        if (data && data.length) {
          const nowTime = new Date().getTime();
          data.forEach((item) => {
            item.thumbs = item.thumbs.split(',');

            // 发布时间
            const timeReduce = nowTime - item.created_at * 1000;
            const time = Math.floor(timeReduce / 1000 / 3600);
            if (time < 24) {
              item.created_at = `${time}小时前`;
            } else {
              item.created_at = momentDate(item.created_at, 'YYYY-MM-DD HH:mm');
            }
          });
          this.items = this.items.concat(data);
          //this.pages.currentPage=current_page+1;
          this.initCount(this.items);
        }
        return {
          perPage: this.pages.perPage,
          currentPage: this.pages.currentPage,
          hasNext: parseInt(last_page) >= parseInt(current_page),
          empty: current_page === 1 && total === 0,
        };
      });
    },
  },
};
</script>

<style lang="less">
.good-wrap {
  padding-bottom: 100rpx;

  /deep/ .prefix {
    margin-right: 6rpx;
    font-size: 20rpx;
    color: #fff;
  }
  .content{
    display: flex;flex-direction: column;
    bottom: 0;
    width: 100%;
    position: fixed;
    .shopping_cart_tips {
      font-size: 25rpx;
      line-height: 32rpx;
      // color: #E20D0D;
      // padding: 24rpx 0 0 33rpx;
      // margin-bottom: 300rpx;
      padding-bottom: 100rpx;
      z-index: 100;
      color: #B02C2C;
      background-color: #fff;
      text-align: center;
      padding-top:15rpx;

    }
  }

  /deep/ .time-box {
    display: inline-block;
    min-width: 28rpx;
    padding: 0 2rpx;
    height: 28rpx;
    line-height: 28rpx;
    text-align: center;
    font-size: 16rpx;
    color: #333;
    vertical-align: middle;
    border-radius: 8rpx;
    box-sizing: border-box;

    &.msg {
      background-color: #793dff;
    }
  }

  /deep/ .time-split {
    font-size: 16rpx;

    &.msg {
      color: #793dff;
    }
  }

  .header {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100vw;
    height: 162rpx;
    padding-top: 12rpx;
    background: #fff;
  }

  .search_row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;
    width: 100%;
    background: #fff;
  }

  .search {
    display: flex;
    align-items: center;
    flex: 1;
    height: 64rpx;
    background: #f5f5f5;
    border-radius: 1000rpx;

    &__icon {
      font-size: 30rpx;
      margin-top: -4rpx;
      margin-right: 12rpx;
    }

    &__input {
      flex: 1;
      align-items: center;
      height: 100%;
      padding: 10rpx 0;
      box-sizing: content-box;
    }
  }

  .tab-box {
    width: 100%;
    background-color: #ffffff;
  }

  .list {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 180rpx;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
  }

  .good_item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    position: relative;
    width: 710rpx;
    padding: 24rpx 20rpx 34rpx 20rpx;
    margin: auto;
    margin-bottom: 20rpx;
    background-color: #ffffff;
    border-radius: 16rpx;

    .left_part {
      margin-right: 14rpx;

      .good_img {
        width: 249rpx;
        height: 220rpx;
        border-radius: 14rpx;
      }
    }

    .right_part {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .right_part_top {
        display: flex;
        align-items: center;

        .pay_type {
          background-color: #ffd7b6;
          border-radius: 8rpx;
          width: 100rpx;
          height: 32rpx;
          font-size: 18rpx;
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;
          margin-right: 23rpx;
        }

        .title {
          font-size: 28rpx;
          color: #000;
          font-weight: bold;
          flex: 1;
        }
      }

      .item_info {
        .good_price_row {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;

          .good_price {
            display: flex;
            flex-direction: row;
            align-items: center;
            color: #ec3737;
            font-weight: 700;

            .price_symbol {
              font-size: 32rpx;
              padding-top: 4rpx;
            }

            .price_text {
              font-size: 42rpx;
              margin-left: 8rpx;
            }
            .price_text_free{
              font-size: 30rpx;
              margin-left: 8rpx;
            }
            
          }
        }

        .operation_row {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          margin-top: 20rpx;

          .count,
          .stock {
            font-size: 24rpx;
            color: #aaa;
          }
        }
      }
    }

  }

  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 0 10rpx;
    z-index: 101;

    .shopping_cart {
      width: 77rpx;
      height: 77rpx;
      margin: 0 20rpx;
    }

    .total_fee_warp {
      flex: 1;
      font-family: PingFangSC-Medium;
      font-size: 24rpx;
      color: #000;

      .total_fee {
        font-size: 34rpx;
      }

      .short_num {
        color: #B02C2C;
      }
    }

    .place_btn {
      background-color: rgba(246, 177, 51, 1);
      border-radius: 40rpx;
      width: 184rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 36rpx;
      font-family: PingFangSC-Semibold;
      color: #ffffff;
    }

  }

  .shopping_cart_layout {
    // background: #fff;
    // padding: 0 30rpx 110rpx;

    .shopping_cart_tips {
      font-size: 23rpx;
      line-height: 32rpx;
      // color: #E20D0D;
      // padding: 24rpx 0 0 33rpx;
      margin-bottom: 300rpx;
      padding-bottom: 100rpx;
      z-index: 100;
      color: red;
      background-color: #fff;
      text-align: center;

    }

    // .shopping_cart_infos {
    //   .good_info {
    //     display: flex;
    //     flex-direction: row;
    //     align-items: center;

    //     .good_img {
    //       width: 120rpx;
    //       height: 120rpx;
    //     }
    //   }
    //}

    .settlement_row {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 120rpx;

      .total_fee {
        font-size: 32rpx;
        font-weight: 700;
      }

      .btn_goto_settlement {
        // width: 240rpx;
        // height: 80rpx;
        // background-color: #FAD84A;
        // color: #fff;
      }
    }
  }
}
</style>
